package com.misty;

import com.misty.synch.Key;
import com.misty.synch.User;
import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * @author iMisty
 * @version 1.0
 * @date 2020/9/4 11:50 下午
 */

public class TestLock {
    ExecutorService es = Executors.newFixedThreadPool(3);

    /**
     * 不使用锁的情况
     */
    @Test
    public void testUnlock(){
        Key key = new Key();
        for (int i = 0;i<3;i++){
            final int storeNumber = i;

            es.execute(new Runnable() {
                @Override
                public void run() {
                    User user = new User( key,storeNumber);
                    user.useKey();
                    System.out.println("我是用户"+storeNumber+"我储存的数字是"+key.getKeyNumber());
                }
            });
        }
        es.shutdown();
    }

    @Test
    public void testlock(){
        Key key = new Key();
        for (int i = 0;i<3;i++){
            final int storeNumber = i;

            es.execute(new Runnable() {
                @Override
                public void run() {
                    User user = new User( key,storeNumber);
                    synchronized (key){
                        user.useKey();
                        System.out.println("我是用户"+storeNumber+"我储存的数字是"+key.getKeyNumber());
                    }
                }
            });
        }
        es.shutdown();
    }

}
